"use strict";

var express = require('express')
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser');

var fs = require('fs')
var moment = require('moment')
var path = require('path')

var app = express()

app.use(bodyParser.json({
    limit: 'lmb' // 指定参数使用json 格式
}))
app.use(bodyParser.urlencoded({
    extended: true
}))

// 设置请求头
// app/json  接口返回json数据
// charset=utf-8 解决json数据中中文乱码
// 设置跨域访问
app.use("*", function (request, response, next) {
    response.setHeader("Access-Control-Allow-Origin", "*"); //*表示允许的域名地址，本地则为'http://localhost'
    response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");

    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", 0);

    // 这行代码会引起：Can't set headers after they are sent.
    // response.writeHead(200, {"Content-Type": "app/json;charset=utf-8"});
    response.setHeader("Content-Type", "application/json;charset=utf-8");
    next();
});

// 自定义日志
app.use(logErrors)
function logErrors(err, req, res, next) {
    if (err) {
        var logDirectory = path.join(__dirname, '../log')
        fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
        //创建错误日志写入流
        const errorStream = fs.createWriteStream(path.join(__dirname, `/log/error-${moment().format('YYYY-MM-DD')}.log`), {flags: 'a'})
        // \r\n用于换行
        errorStream.write(`[error] url: ${req.url} message: ${err.stack} \r\n`)
        errorStream.end()
    }
    next(err)
}

// 使用cookie
app.use(cookieParser())


// 添加全局中间件


// 注册路由表
var user = require('./../router/user')
var application = require('../router/app/application')
var appversion = require('./../router/appversion')
var patch = require('./../router/patch')
var logreport = require('./../router/logreport')

app.use('/user', user)
app.use('/application', application)
app.use('/appversion', appversion)
app.use('/patch', patch)
app.use('/logreport', logreport)

// 定义错误处理中间件
app.use(function (error, req, res, next) {
    console.error(error.stack);
    // res.status(500).send('Something broke!');
})

exports.createServer = function () {
    var server = app.listen(8081, function () {
        var host = server.address().address
        var port = server.address().port
        console.log("访问地址为 http://%s:%s", host, port)
    })
}

